package com.itwang.common;

import com.itwang.common.IpGeter;
import com.itwang.handler.ConsumerException;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.ResourceBundle;

//邮件发送
public class SendEmail {
	/**
	 * 配置发送基本参数
	 * 发件人邮箱的SMTP服务器地址
	 * 前三个不可更改
	 */
	private static String MyEmail;//开启授权码的邮箱
	private static String AuthorizationCode;//授权码
	private static String SMTPEmail;// 网易163邮箱的 SMTP 服务器地址
	private static String harvestEmail;// 收件人邮箱
	
	static {
		MyEmail = PropertiesUtil.getKey("sendEmailAddress");
		AuthorizationCode = PropertiesUtil.getKey("AuthorizationCode");
		SMTPEmail = PropertiesUtil.getKey("SMTPEmail");
		harvestEmail = PropertiesUtil.getKey("harvestEmail");
		
		if (MyEmail == null || MyEmail == "") {
			throw new ConsumerException("发件人地址为无效");
		}
		if (AuthorizationCode == null || AuthorizationCode == "") {
			throw new ConsumerException("授权码为无效");
		}
		if (SMTPEmail == null || SMTPEmail == "") {
			throw new ConsumerException("SMTP邮件服务器地址为无效");
		}
		if (harvestEmail == null || harvestEmail == "") {
			throw new ConsumerException("收件人地址为无效");
		}
	}
	
	
	public static void sendMessage(String msg) throws Exception {
		//创建连接邮件服务器的参数配置
		Properties props = new Properties();// 参数配置
		props.setProperty("mail.smtp.host", SMTPEmail);// 发件人的邮箱的 SMTP 服务器地址
		props.setProperty("mail.smtp.auth", "true");// 需要请求认证
		props.setProperty("mail.transport.protocol", "smtp");
		//根据配置创建会话对象和邮件服务器交互
		Session session = Session.getInstance(props);
		if (Integer.valueOf(PropertiesUtil.getKey("logClass")) >= 4) {
			// session.setDebug(true);// 设置为debug模式, 可以查看详细的发送日志
			session.setDebug(true);
		}
		//创建邮件
		MimeMessage message = createEmail(session, MyEmail, harvestEmail, msg);
		//使用Session获取邮件传输对象
		Transport transport = session.getTransport();
		//使用邮箱账号和密码连接邮件服务器
		transport.connect(MyEmail, AuthorizationCode);
		//发送邮件
		
		transport.sendMessage(message, message.getAllRecipients());
		//关闭连接
		transport.close();
		
	}
	
	/**
	 * 创建邮件
	 */
	public static MimeMessage createEmail(Session session, String sendMail, String receiveMail, String ips) throws Exception {
		//创建一封邮件
		MimeMessage message = new MimeMessage(session);
		//发件人
		message.setFrom(new InternetAddress(sendMail, "IP看门狗", "UTF-8"));
		//收件人
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "亲爱的主人", "UTF-8"));
		//邮件主题
		message.setSubject("发现您的服务器IP变动", "UTF-8");
		//邮件正文
		
		message.setContent(ips, "text/html;charset=UTF-8");
		//设置发件时间
		message.setSentDate(new Date());
		//保存设置
		message.saveChanges();
		return message;
	}
}
